import { request } from 'utils/request';
import type { ApiResponse } from 'types/common';
import type {
  GraphItem,
  CreateGraphParams,
  GraphDetail,
  GraphListParams,
  TestDatabaseConnectionParams,
  SaveDatabaseConfigParams,
  BuildGraphParams,
  GetDataSourceTablesParams,
  DataSourceTableInfo,
  BuildGraphProgress,
} from 'types/graph-builder';

// API 方法
export const graphBuilderApi = {
  // 获取图谱列表
  getGraphList(params: GraphListParams) {
    return request.get<
      any,
      ApiResponse<{ count: number; results: GraphItem[] }>
    >('/graphs/', { params });
  },

  // 创建图谱
  createGraph(data: CreateGraphParams) {
    return request.post<any, ApiResponse<GraphItem>>('/graphs/generate/', data);
  },

  // 测试数据库链接
  testDatabaseConnection(data: TestDatabaseConnectionParams) {
    return request.post<any, ApiResponse<null>>(
      '/graphs/test_connection/',
      data
    );
  },

  // 保存数据库配置信息
  saveDatabaseConfig(id: string, data: SaveDatabaseConfigParams) {
    return request.put<any, ApiResponse<null>>(
      `/graphs/${id}/data_source/`,
      data
    );
  },

  // 读取数据库中数据列表
  getDataSourceTables(id: number, data: GetDataSourceTablesParams) {
    return request.get<
      any,
      ApiResponse<{ count: number; results: DataSourceTableInfo[] }>
    >(`/graphs/${id}/data_source_tables/`, {
      params: data,
    });
  },

  // 立即构建图谱
  buildGraph(id: string, data: BuildGraphParams) {
    return request.post<any, ApiResponse<null>>(`/graphs/${id}/build/`, data);
  },

  // 获取构建进度
  getBuildProgress(id: string) {
    return request.get<any, ApiResponse<BuildGraphProgress>>(`/graphs/${id}/progress/`);
  },

  // 获取图谱详情
  getGraphDetail(graphId: string) {
    return request.get<any, ApiResponse<GraphDetail>>(`/graphs/${graphId}/info/`);
  },

  // 删除图谱
  deleteGraph(graphId: string) {
    return request.delete<any, ApiResponse<null>>(`/graphs/${graphId}/delete/`);
  },

  // 非结构化构建文件上传
  uploadFile(id: string, data: FormData) {
    return request.post<any, ApiResponse<null>>(
      `/graphs/${id}/upload_file/`,
      data,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }
    );
  },
};
